<template>
	<div>
		<div class="banner">
			<image :src="hdinfo.banner" mode="widthFix"></image>
		</div>
		<div class="searchBox">
			<u-search shape="round" v-model="searchVal"></u-search>
		</div>
		<view class="toupiao_container">
			<div class="items">
				<div class="item" v-for="(item,index) in endList" :key="index" v-if="searchVal ? item.name.indexOf(searchVal) != -1 : true">
					<div class="numBox">NO.{{index + 1}}</div>
					<u--image :src="imgLink + item.img" width="100%" @click="showImg(imgLink + item.img)">
					  <template v-slot:loading>
					    <u-loading-icon color="red"></u-loading-icon>
					  </template>
					</u--image>
					<div class="bottom">
						<h3>{{item.name}}</h3>
						<div class="btn" v-if="outTime"><u-button type="error" size="mini" text="投票结束" disabled="true"></u-button></div>
						<div class="btn" v-else>
							<u-button type="error" size="mini" text="投票" @click="checkToupiao(item)" v-if="qdNum == 0"></u-button>
							<u-button type="error" size="mini" text="今天已投票" disabled="true" v-else></u-button>
						</div>
					</div>
					<div class="toupiaoInfo">
						<u-tag :text="item.hdps + ' 票，距上一名差' + (index == 0 ? 0 : endList[index - 1].hdps - item.hdps) + '票'" plain  type="warning"></u-tag>
					</div>
				</div>
			</div>
		</view>
		<u-modal :show="showConfirm" :showCancelButton="true" :showConfirmButton="true" :title="'确认投票？'" content="一旦确定无法更改~~" @cancel="showConfirm = false" :closeOnClickOverlay="true" @confirm="toupiao()"></u-modal>
	
		<div class="chatBox" @click="showImg('https://www.baixuemianshi.com/zhuanti/toupiao/images/zixun.jpg')">
			<u-icon size="26" :name="chatIcon" color="#2979ff"></u-icon>
		</div>
		<div class="telBox" @click="contactus">
			<u-icon size="26" :name="telIcon" color="#ff9900"></u-icon>
		</div>
		
		<u-popup :show="showPop" mode="center" @close="showPop = false" :closeable="true">
			<view class="popcontent">
				<h3>投票规则</h3>
				<p>{{hdinfo.guize}}</p>
			</view>
		</u-popup>
		
		<div class="loadBox" v-if="searchLoading">
			<u-loading-icon size="36" mode="circle" :vertical="true" color="red" text="加载中..." textSize="20"></u-loading-icon>
		</div>
		
		
		<div class="fixBottom" v-if="checkSc">
			<div class="container">
				<u-button type="error" size="small" text="我要参加" @click="newUser()"></u-button>
			</div>
		</div>
		
	
	</div>
</template>

<script>
	const MAX_LIMIT = 20
	import { mapActions } from 'vuex';
	const db = wx.cloud.database()
export default {
	name: 'headcomd',
	data() {
		return {
			openid: "",
			hdid: "",
			hdinfo:{},
			peopleList: [],
			showList: [],
			imgLink: 'https://www.baixuemianshi.com/zhuanti/toupiao/upload/',
			outTime: false,
			time: "",
			qdNum: 0,
			stop: false,
			tpList: [],
			showConfirm: false,
			toupiaoItem: {},
			chatIcon: "chat",
			telIcon: "phone",
			searchVal: "",
			showPop: true,
			endList: [],
			dateEnd: false,
			searchLoading: true
		};
	},
	onShareAppMessage(options) {
		let that = this
		var shareObj = {
		    title: that.hdinfo.biaoti,    // 默认是小程序的名称(可以写slogan等)
		    path: '/pages/huodong/vote_person/index?hdid=' + that.hdid,    // 默认是当前页面，必须是以‘/'开头的完整路径
		    imageUrl: that.hdinfo.shareImg,   //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
		    success: function(res){
		      // 转发成功之后的回调
		      if(res.errMsg == 'shareAppMessage:ok'){
		      }
		    }
		};
		return shareObj
	},
	onShareTimeline(res) {
		return {
			title: this.hdinfo.biaoti,
			path: 'pages/huodong/vote_person/index?hdid=' + this.hdid,
			imageUrl: 'https://www.baixuemianshi.com/zhuanti/images/logo_squer.jpg'
		}
	},
	onLoad(options) {
		this.hdid = options.hdid;
	},
	computed: {
		userphone() {
			return this.$store.getters.userphone ? this.$store.getters.userphone : '';
		},
		checkSc(){
			let that = this
			const time = new Date().getTime() / 1000
			const sTime = new Date(that.hdinfo.scTime).getTime() / 1000
			
			
			let oId = that.peopleList.map(item => item._openid)
			if(oId.includes(that.openid)){
				return false
			}
			
			return time < sTime
		},
	},
	mounted() {
		let that = this
		setInterval(()=>{
			that.chatIcon = that.chatIcon == 'chat' ? 'chat-fill' : 'chat'
			that.telIcon = that.telIcon == 'phone' ? 'phone-fill' : 'phone'
		},1000)
	},
	created() {
		let that = this
		
		let day = new Date()
		let y = day.getFullYear()
		let m = day.getMonth() + 1
		let d = day.getDate()
		that.time = y + '-' + m + '-' + d
	},
	onShow() {
		this.peopleList = []
		if(this.openid){
			this.getHdinfo()
			this.getnum()
		}else{
			this.getopenid()
		}
	},
	methods: {
		...mapActions(['LogSetPhone']),
		contactus() {
			wx.makePhoneCall({
				phoneNumber: '18646042617'
			});
		},
		getopenid() {
			let that = this;
			wx.cloud.callFunction({
				name: 'getopenid',
				data: {},
				complete: res => {
					that.openid = res.result.openid
					this.getHdinfo()
					this.getnum()
				}
			});
		},
		async getnum(){
			let that = this
			const qdnum = await db.collection("toupiao_user").where({hdid: that.hdid,openid: that.openid,time: that.time}).count()
			that.qdNum = qdnum.total
			
			that.stop = false
		},
		getHdinfo(){
			let that = this
			db.collection('toupiao_list').doc(that.hdid).get({
				success: function(res){
					that.hdinfo = res.data
					that.getList(0)
				}
			})	
		},
		getList(page){
			let that = this
			db.collection('toupiao_options').skip(page * 20).limit(20).where({
				hdid: that.hdid
			}).get({
				success:res => {
					if(res.data.length > 0){
						that.peopleList = that.peopleList.concat(res.data)
						let p = page + 1
						that.getList(p)
					}else{
						that.checkTime()
					}
				}
			})
		},
		checkTime(){
			let that = this
			const time = new Date().getTime() / 1000
			const sTime = new Date(that.hdinfo.time1).getTime() / 1000
			const eTime = new Date(that.hdinfo.time2).getTime() / 1000
			if(time < sTime || time > eTime){
				that.outTime = true
			}else{
				that.outTime = false
			}
			that.getToupiaouser()
		},
		toupiao(){
			let that = this
			if(!that.userphone){
				uni.navigateTo({
					url: '../../my/login?navTlt=' + encodeURIComponent(that.hdinfo.name + '?name=空')
				});
				return
			}
			if(that.stop){
				wx.showToast({
					icon: 'error',
					title: '点的太快啦'
				})
				return
			}
			that.stop = true
			db.collection('toupiao_user').add({
				data:{
					hdid: that.hdid,
					openid: that.openid,
					optionid: that.toupiaoItem._id,
					time:that.time,
					phone: that.userphone
				},
				success: function(res){
					that.getnum()
					that.getToupiaouser()
				}
			})
		},
		async getToupiaouser(){
			let that = this
			await Promise.all(that.peopleList.map(async (item,index) => {
				await that.getCloud(item._id,index)
			}))
			that.endList = that.peopleList.sort(that.sortBy('hdps',false))
			that.searchLoading = false
		},
		async getCloud(id,index){
			let that = this
			const countResult = await db.collection('toupiao_user').where({hdid: that.hdid,optionid: id}).count()
			
			that.$set(that.peopleList[index],'hdps',countResult.total)
			
		},
		getVote(info){
			let a = this.tpList.filter(item => item.optionid == info._id)
			return a.length
		},
		showImg(img){
			wx.previewImage({
				urls: [img], //需要预览的图片http链接列表，注意是数组
				current: '', // 当前显示图片的http链接，默认是第一个
				success: function(res) {},
				fail: function(res) {},
				complete: function(res) {}
			});
		},
		sortBy(attr, rev) {
			//第二个参数没有传递 默认升序排列
			if (rev == undefined) {
				rev = 1;
			} else {
				rev = rev ? 1 : -1;
			}

			return function(a, b) {
				a = parseInt(a[attr]);
				b = parseInt(b[attr]);
				if (a < b) {
					return rev * -1;
				}
				if (a > b) {
					return rev * 1;
				}
				return 0;
			};
		},
		checkToupiao(item){
			let that = this
			wx.showModal({
				title:"确认投票？",
				content: '一旦选择无法修改',
				success (res) {  
				    if (res.confirm) {  
						that.toupiaoItem = item
						that.searchLoading = true
						that.toupiao()
				    } else if (res.cancel) {  
						console.log('用户点击取消')  
				    }  
				}
			})
			
		},
		newUser(){
			uni.navigateTo({
				url:'./user?hdid=' + this.hdid
			})
		}
	},
	components: {}
};
</script>

<style>
@import url("./index.css");

</style>

